package com.mk.service.web;

import act.controller.Controller;
import cn.hutool.core.date.DateUtil;
import com.github.d925529.apidoc.annotation.*;
import com.mk.domain.TCart;
import com.mk.domain.TProduct;
import com.mk.domain.TProductSpec;
import com.mk.enums.GlobalValues;
import com.mk.exception.UserException;
import com.mk.interceptor.ITranslate;
import com.mk.util.MapUtil;
import com.mk.util.S2;
import org.osgl.mvc.annotation.DeleteAction;
import org.osgl.mvc.annotation.GetAction;
import org.osgl.mvc.annotation.PostAction;
import org.osgl.mvc.annotation.With;
import org.osgl.util.S;

import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.*;

/**
 * 说明：购物车前台接口
 * 作者：anonymous 
 * 日期：2018-10-25 15:0:13 
 * 版本：1.0.0
 */
@Controller("tCart")
@Api(group = "wb",title = "购物车服务", path = "/tCart")
@SuppressWarnings("unused")
public class TCartService extends BaseWebService {
    @Inject
    private TCart.Mapper tCartMapper;
    @Inject
    private TProductSpec.Mapper tProductSpecMapper;
    @Inject
    private ZMbAddressService zMbAddressService;
    @Inject
    private TOrderService tOrderService;
    //方法权限过滤使用ILogin.class
    //这个类在父类中有声明,不需要引入包

    /**
     * 添加购物车
     * @param list
     * @return
     */
    @PostAction("addToCart.json")
    @With({WbILogin.class, ITranslate.class})
    public Integer addToCart(List<TCart> list){
//        String psid,Integer cartnumber
        if(list==null||list.size()==0){
            throw new UserException("请选择商品");
        }
        list.forEach(tCart -> {
            String psid = tCart.getPsid();
            Integer cartnumber = tCart.getCartnumber();
            TCart param = new TCart();
            param.setMid(me.getMid());
            param.setPsid(psid);
            TCart cart = tCartMapper.templateOne(param);
            if(cart!=null){
                tCartMapper.executeUpdate("update t_cart set cartnumber=cartnumber+? where cartid=?",cartnumber, cart.getCartid());
            }else {
                TProduct product = tProductSpecMapper.queryProductByPsid(psid);
                cart = new TCart();
                cart.setCartid(S2.UUID());
                cart.setMid(me.getMid());
                cart.setPsid(psid);
                cart.setPdid(product.getPdid());
                cart.setBrid(product.getBrid());
                cart.setCartdate(DateUtil.now());
                cart.setCartnumber(cartnumber);
                tCartMapper.insert(cart);
            }
        });
        return list.size();
    }

    @DeleteAction("deleteByCartid.json")
    @With({WbILogin.class,ITranslate.class})
    public Integer deleteByCartid(String cartid){
        return tCartMapper.deleteById(cartid);
    }

    @GetAction("cartCount.json")
    @With({WbILogin.class})
    public Long cartCount(){
        TCart cart = new TCart();
        cart.setMid(me.getMid());
        return tCartMapper.templateCount(cart);
    }

    /**
     * 购物车中商品种类数量
     * @return
     */
    @GetAction("cartList.json")
    @With({WbILogin.class, ITranslate.class})
    public List<Map<String,Object>> cartList(){
        List<Map<String,Object>> list = tCartMapper.cartList(me.getMid());
        if(list!=null&&list.size()>0){
            return list;
        }
        return new ArrayList<>();
    }

    /**
     * 确认订单
     * iscart是否购物车下单
     * @param list
     * @param iscart
     * @return
     * {
     * address:{}
     * confirmlist: [{
     *  pdid:''
     *  pdname:''
     *  img:''
     *  skulist:[{
     *      psid:''
     *      detailrnumber:''
     *      psname:''
     *      psprice:''
     *      pdunit:''
     *      detailtotal:''
     *      },
     *      ...
     *  ]
     *
     * },
     * ...
     * ]}
     *
     */
    @PostAction("confirmList.json")
    @With({WbILogin.class, ITranslate.class})
    public Map<String, Object> confirmList(List<TCart> list, String iscart) {
        Map<String,Object> result = new HashMap<>();
        List<Map<String, Object>> confirmlist = new ArrayList<>();
        if (S.eq(iscart, GlobalValues.FLAG_1.value())) {
            List<String> cartids = new ArrayList<>();
            list.forEach(cart -> cartids.add(cart.getCartid()));
            List<Map<String, Object>> listConfirm = tCartMapper.confirmCartList(me.getMid(), cartids);
            Set<String> set = new HashSet();
            listConfirm.forEach(map->{
                if(set.add(MapUtil.getStr(map,"pdid"))){
                    Map<String,Object> product = new HashMap<>();
                    product.put("pdid",map.get("pdid"));
                    product.put("pdname",map.get("pdname"));
                    product.put("img",map.get("img"));
                    List<Map<String,Object>> skulist = new ArrayList<>();
                    skulist.add(subMapHandle(list, map));
                    product.put("skulist",skulist);
                    confirmlist.add(product);
                }else {
                    Map<String,Object> subMap = confirmlist.get(confirmlist.size()-1);
                    List<Map<String,Object>> skulist = (List<Map<String, Object>>) subMap.get("skulist");
                    skulist.add(subMapHandle(list, map));
                }
            });
            result.put("confirmlist",confirmlist);
        }else {
           //直接下单
            if(list!=null&&list.size()>0){
                TCart cart = list.get(0);
                List<String> psids = new ArrayList<>();
                list.forEach(tCart->{
                    psids.add(tCart.getPsid());
                });
                List<Map<String,Object>> pdList = tProductSpecMapper.queryProductSecByPsids(psids);
                Map<String,Object> map = new HashMap<>();
                if(pdList.size()>0){
                    map = pdList.get(0);
                }
                Map<String,Object> product = new HashMap<>();
                product.put("pdid",map.get("pdid"));
                product.put("pdname",map.get("pdname"));
                product.put("img",map.get("img"));
                List<Map<String,Object>> skulist = new ArrayList<>();
                pdList.forEach(subMap->{
                    skulist.add(subMapHandle(list, subMap));
                });
                product.put("skulist",skulist);
                confirmlist.add(product);
                result.put("confirmlist",confirmlist);
            }
        }
        result.put("address", zMbAddressService.defaultAddress());
        result.put("discount", tOrderService.getDiscount());

        return result;
    }

    /**
     * 处理子类
     * @param list
     * @param map
     */
    private Map<String,Object> subMapHandle(List<TCart> list, Map<String, Object> map) {
        map.remove("pdid");
        map.remove("pdname");
        map.remove("img");
        TCart cart = list.stream().filter(d-> S.eq(d.getPsid(), MapUtil.getStr(map,"psid"))).findFirst().get();
        map.put("detailrnumber",cart.getCartnumber());
        map.put("detailtotal",new BigDecimal(cart.getCartnumber()).multiply(MapUtil.getDg(map,"psprice",BigDecimal.ZERO)));
        return map;
    }


}
